package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.chatConfig.ChatWebSocketHandler;
import com.example.pojo.ChatLog;
import com.example.pojo.Result;
import com.example.service.ChatLogService;
import com.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Author fantasy
 * @Date 2025/1/20 22:23
 **/


@RestController
@RequestMapping("/chat")
public class ChatLogController {

    @Autowired
    private ChatLogService chatLogService;


    @PostMapping("/add")
    public Result addChatLog(@RequestBody List<ChatLog> chatLogs) throws IOException {
        Map<String, Object> o = ThreadLocalUtil.get();
        String username = (String) o.get("username");
        ChatLog chatLog = chatLogs.get(0);
        String friend = chatLog.getFriend();
        chatLog.setUsername(username);
        chatLogService.addChatLog(chatLog);
        chatLog.setSelf(false);
        chatLog.setUsername(friend);
        chatLog.setFriend(username);
        chatLogService.addChatLog(chatLog);
        JSONObject map = new JSONObject();
        map.put("content", chatLog.getContent());
        map.put("from", username);
        map.put("to", friend);
        ChatWebSocketHandler.sendMessageToAll(JSON.toJSONString(map));
        return Result.success();
    }

    @RequestMapping("/get")
    public Result getChatLog(@RequestBody JSONObject json){
        Map<String, Object> o = ThreadLocalUtil.get();
        String username = (String) o.get("username");
        HashMap map = new HashMap();
        map.put("username", username);
        map.put("friend", json.getString("friend"));
        List<ChatLog> chatLog = chatLogService.getChatLog(map);
        return Result.success(chatLog);
    }
}
